<!-- 
 * @Author: guanpf 992093924@qq.om
 * @Date: 2023-07-19 10:55:23
 * @LastEditTime: 2023-10-22 21:57:58
 * @LastEditors: guanpf
 * @Description: 
 * @FilePath: /ZCGL_WX/src/views/main/asset/views/registration.vue
 -->
<template>
  <div class="registration">
    <group class="form">
      <x-input
        title="资产数字ID"
        v-model="form.assetCode"
        text-align="right"
        required
        placeholder="请输入"
      ></x-input>
      <div class="scan">
        <div class="scan-content" @click="scanCode">
          <img src="@/assets/images/asset/scan.png" alt="" /> <span>扫一扫</span>
        </div>
      </div>
      <x-input
        title="资产名称"
        v-model="form.assetName"
        text-align="right"
        required
        :clearable="false"
        placeholder="请输入"
      ></x-input>
      <div class="block-tips">
        <div
          v-for="(item, index) in nameList"
          :class="form.assetName == item ? 'active-tips' : ''"
          @click="form.assetName = item"
          :key="index"
        >
          {{ item }}
        </div>
      </div>
      <!-- <popup-picker
        :key="1"
        title="资产分类"
        :data="classList"
        v-model="form.classId"
        @on-change="changeClass"
        show-name
        placeholder="请选择资产分类"
      ></popup-picker> -->
      <popup-picker
        ref="pickerClass"
        title="资产分类"
        :data="classList"
        :columns="2"
        v-model="form.classId"
        @on-change="changeClass"
        show-name
      ></popup-picker>
      <!-- 品牌型号选择 -->
      <cell title="品牌型号" is-link>
        <span slot @click="tagShow = true">请输入或选择品牌型号</span>
      </cell>
      <div class="block-tips">
        <div v-for="(item, index) in checkTags" class="tips-line" :key="index">
          {{ item }}
        </div>
      </div>
      <x-input
        title="摆放位置"
        v-model="form.place"
        text-align="right"
        required
        placeholder="请输入"
      ></x-input>
      <div class="block-tips">
        <div
          v-for="(item, index) in placeList"
          :class="form.place == item ? 'active-tips' : ''"
          :key="index"
          @click="form.place = item"
        >
          {{ item }}
        </div>
      </div>
      <datetime v-model="form.indate" format="YYYY-MM-DD HH:mm" title="有效期"></datetime>
      <!-- <template v-if="assetId">
        <cell title="使用人" :value="form.name"></cell>
      </template>
      <template v-else>
        <wx-select-person
          title="使用人"
          @getPersonList="getPersonList"
        ></wx-select-person>
      </template> -->
      <wx-select-person
        title="使用人"
        :selectUserNames="form.useName"
        @getPersonList="getPersonList"
      ></wx-select-person>
      <!-- <x-input title="使用人" v-model="form.useId" placeholder="请输入"></x-input> -->
      <x-input
        title="价格"
        keyboard="number"
        text-align="right"
        v-model="form.price"
        placeholder="请输入"
      ></x-input>
      <x-textarea
        class="mark"
        :max="100"
        v-model="form.assetExplain"
        placeholder="请输入备注信息，100字以内"
      >
        <div slot="label">说明</div>
      </x-textarea>
      <!-- 上传照片 -->
      <div class="upload-img">上传照片</div>
      <div class="file-box flex-start">
        <i class="fa fa-plus-square-o" v-if="imageList.length == 0">
          <input type="file" accept="image/*" ref="imageUpload" @change="uploadChange" />
        </i>
        <div id="instruction-pic">
          <template v-if="imageList.length > 0">
            <div
              v-for="(item, index) in imageList"
              :key="index"
              class="instruction-pic-item"
            >
              <img :src="item.fileUrl" alt="" />
              <i class="fa fa-close" @click="imageList.splice(index, 1)"></i>
            </div>
          </template>
        </div>
      </div>
    </group>
    <div class="submit-box" v-if="!tagShow">
      <x-button class="submit-btn" @click.native="submitAdd">{{
        assetId ? "保存" : "添加"
      }}</x-button>
    </div>
    <!-- 选择添加品牌型号 -->
    <popup
      v-model="tagShow"
      position="bottom"
      class="choose-tag"
      should-scroll-top-on-show
    >
      <group>
        <checklist
          title="选择品牌型号"
          required
          :options="tagList"
          v-model="selectTags"
          @on-change="changeTag"
        ></checklist>
        <div class="add-tag">
          <x-input
            v-model.trim="newTag"
            required
            placeholder="请输入品牌型号名称"
          ></x-input>
          <x-button size="mini" class="add-tag-btn" @click.native="addTag"
            >手动添加</x-button
          >
        </div>
        <div class="check-tags-box">
          <div class="title">已添加品牌型号</div>
          <div class="check-tags">
            <template v-if="selectTags.length > 0 || addTags.length > 0">
              <div
                v-for="(item, index) in selectTags"
                :key="index"
                @click="delSelectTags(index)"
              >
                {{ item }}
              </div>
              <div
                v-for="(item, index) in addTags"
                :key="index + item"
                @click="delAddTags(index)"
              >
                {{ item }}
              </div>
            </template>
          </div>
        </div>
      </group>
      <div style="padding: 15px">
        <x-button
          class="confirm-tag-btn"
          @click.native="setCheckTags"
          plain
          type="primary"
          >确定</x-button
        >
      </div>
    </popup>
  </div>
</template>

<script>
import WxSelectPerson from "@/components/common/wx-select-person";
import AssetApi from "@/api/asset.js";
import {
  Group,
  PopupPicker,
  XInput,
  Datetime,
  XTextarea,
  XButton,
  Cell,
  Popup,
  Checklist,
} from "vux";
import { mapActions } from "vuex";
export default {
  components: {
    Checklist,
    Popup,
    Cell,
    WxSelectPerson,
    PopupPicker,
    Group,
    XInput,
    Datetime,
    XTextarea,
    XButton,
  },
  data() {
    return {
      assetId: "",
      assetCode: "",
      form: {
        assetCode: "",
        assetName: "",
        place: "",
        indate: "",
        useId: "DaFei",
        useName: "",
        price: "",
        assetExplain: "",
        classId: [],
      },
      nameList: [],
      placeList: [],
      classList: [],
      tagShow: false,
      tagList: [],
      selectTags: [],
      addTags: [],
      checkTags: [],
      newTag: "",
      imageList: [],
    };
  },
  mounted() {
    this.findTenPlace();
    this.findTenName();
    if (this.$route.query.id) {
      this.assetId = this.$route.query.id;
      this.getInfo(this.$route.query.id);
    }
    if (this.$route.query.code) {
      this.assetCode = this.$route.query.code;
      this.getInfoByCode(this.$route.query.code);
    }
    console.log(242, this.$route.params);
    if (this.$route.params.info) {
      let _info = this.$route.params.info;
      console.log(250, _info);

      this.form = {
        assetCode: "",
        assetName: _info.assetName || "",
        place: _info.place || "",
        useId: _info.useId || "",
        useName: _info.useName || "",
        price: _info.price || "",
        assetExplain: _info.assetExplain || "",
        classId: [_info.parentId,_info.classId] || [],
      };
      this.form.indate = _info.indate || "" 
      console.log(261, this.form);
      this.selectTags = this.checkTags = _info.tags.split(",");
      this.imageList = _info.fileList || [];
    } else {
      if (this.$store.state.user.registration.place) {
        this.form.place = this.$store.state.user.registration.place;
      }
      if (this.$store.state.user.registration.indate) {
        this.form.indate = this.$store.state.user.registration.indate;
      }
      if (this.$store.state.user.registration.useName) {
        this.form.useName = this.$store.state.user.registration.useName;
        this.form.useId = this.$store.state.user.registration.useId;
      }
    }
    this.assetClass();
  },
  methods: {
    delAddTags(index) {
      this.addTags.splice(index, 1);
    },
    delSelectTags(index) {
      this.selectTags.splice(index, 1);
    },
    changeClass(val) {
      let _params = {
        classId: val[1]?val[1]:val[0],
      };
      AssetApi.getTagList(_params).then((res) => {
        if (res.code == "0000") {
          this.tagList = res.data || [];
        }
      });
    },
    setCheckTags() {
      this.checkTags = [...this.selectTags, ...this.addTags];
      this.tagShow = false;
    },
    addTag() {
      if (this.newTag) {
        if (this.addTags.includes(this.newTag)) {
          this.$vux.toast.show({
            text: "品牌型号已存在请重新输入",
            type: "warn",
          });
        } else {
          this.addTags.push(this.newTag);
          this.newTag = "";
        }
      } else {
        this.$vux.toast.show({
          text: "请输入品牌型号",
          type: "warn",
        });
      }
    },
    // 选择品牌型号
    changeTag(val, label) {
      console.log("change", val, label);
    },
    ...mapActions("user", ["registration"]),
    getInfo(id) {
      AssetApi.getAssetInfo({ id: id }).then((res) => {
        this.form = {
          assetCode: res.data.assetCode || "",
          assetName: res.data.assetName || "",
          place: res.data.place || "",
          indate: res.data.indate || "",
          useId: res.data.useId || "",
          useName: res.data.useName || "",
          price: res.data.price || "",
          assetExplain: res.data.assetExplain || "",
          classId: [res.data.parentId,res.data.classId] || [],
        };
        this.selectTags = this.checkTags = res.data.tags.split(",");
        this.imageList = res.data.fileList || [];
      });
    },
    getInfoByCode(code) {
      console.log(139, code);
      AssetApi.getAssetDetail({ assetCode: code }).then((res) => {
        this.assetId = res.data.assetId;
        this.form = {
          assetCode: res.data.assetCode || "",
          assetName: res.data.assetName || "",
          place: res.data.place || "",
          indate: res.data.indate || "",
          useId: res.data.useId || "",
          useName: res.data.useName || "",
          price: res.data.price || "",
          assetExplain: res.data.assetExplain || "",
          classId: [res.data.parentId,res.data.classId] || [],
        };
        this.selectTags = this.checkTags = res.data.tags.split(",");
        this.imageList = res.data.fileList || [];
      });
    },
    getPersonList(value) {
      let userIds = value[0].id; // 已选的单个成员ID
      let userNames = value[0].name; // 已选的单个成员ID
      this.form.useId = userIds;
      this.form.useName = userNames;
    },
    findTenPlace() {
      AssetApi.findTenPlace().then((res) => {
        if (res.code == "0000") {
          this.placeList = res.data || [];
        }
      });
    },
    findTenName() {
      AssetApi.findTenName().then((res) => {
        if (res.code == "0000") {
          this.nameList = res.data || [];
        }
      });
    },
    scanCode() {
      let _this = this;
      wx.scanQRCode({
        desc: "scanQRCode desc",
        needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是条形码（一维码），默认二者都有
        success: function (res) {
          let strStartIndex = res.resultStr.lastIndexOf("=") + 1;
          let str = res.resultStr.substring(strStartIndex, res.resultStr.length);
          _this.form.assetCode = str;
          // 回调
          // var result = res.resultStr;//当needResult为1时返回处理结果
        },
        error: function (res) {
          if (res.errMsg.indexOf("function_not_exist") > 0) {
            alert("版本过低请升级");
          }
        },
      });
    },
    submitAdd() {
      if (!this.form.assetCode) {
        this.$vux.toast.show({
          text: "请输入资产数字ID",
          type: "warn",
        });
      } else if (!this.form.assetName) {
        this.$vux.toast.show({
          text: "请输入资产名称",
          type: "warn",
        });
      } else if (this.form.classId.length == 0) {
        this.$vux.toast.show({
          text: "请选择资产分类",
          type: "warn",
        });
      } else if (!this.form.place) {
        this.$vux.toast.show({
          text: "请输入摆放位置",
          type: "warn",
        });
      } else {
        let _params = JSON.parse(JSON.stringify(this.form));
        if (this.assetId) {
          _params.assetId = this.assetId;
        }
        if (this.imageList.length > 0) {
          let _imgs = this.imageList.map((item) => {
            return item.fileId;
          });
          _params.imgs = _imgs;
        }
        _params.parentId = this.form.classId[0] || '';
        _params.classId = this.form.classId[1]?this.form.classId[1]:this.form.classId[0];
        _params.tags = this.checkTags.toString();
        if(this.$refs.pickerClass&&this.$refs.pickerClass.getNameValues()){
          let classArr = this.$refs.pickerClass.getNameValues().split(' ')
          _params.parentName = classArr[0]
          _params.className = classArr[1]
        }
        AssetApi[this.assetId ? "assetUpdate" : "assetAdd"](_params).then((res) => {
          if (res.code == "0000") {
            this.$vux.toast.show({
              text: "资产" + `${this.assetId ? "保存" : "添加"}` + "成功",
            });
            let _registration = {
              place: this.form.place,
              indate: this.form.indate,
              useName: this.form.useName,
              useId: this.form.useId,
            };
            this.registration(_registration);
            this.$router.push("assetHome");
          }
        });
      }
    },

    assetClass() {
      let _params = {
        pageNum: 1,
        pageSize: 1000,
      };
      AssetApi.assetClassTree(_params).then((res) => {
        if (res.code == "0000") {
          let _classList = [];
          let resData = res.data;
          for (let i in resData) {
            let temp = {
              name: resData[i].name,
              value: resData[i].id,
              parent: 0,
            };
            _classList.push(temp);
            for (let j in resData[i].children) {
              let temp1 = {
                name: resData[i].children[j].name,
                value: resData[i].children[j].id,
                parent: resData[i].id,
              };
              _classList.push(temp1);
            }
          }
          this.classList = _classList;
        }
      });
    },
    // 上传照片
    async uploadChange(e) {
      var elem = document.getElementById("instruction-pic");
      var files = e.target.files[0];
      let imageItem = {
        id: "",
        src: "",
      };
      if (files && files.size) {
        var size = files.size / 1000 / 1024;
        // 如果图片大于2M则重新上传，这里e.target.files[0].size单位是b
        // if (size > 2) {
        //   alert("图片大于2M,请重新上传");
        //   return;
        // }
        // 如果上传的不是图片格式，提示请选择图片
        var rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
        if (!rFilter.test(files.type)) {
          alert("请选择图片格式!");
        }
        var reader = new FileReader();
        reader.readAsDataURL(files);
        reader.onloadstart = function () {
          console.log("图片正在上传处理......");
        };
        this.glRequest.uploadFile(files).then((res) => {
          if (res.code == "0000") {
            imageItem.fileId = res.data.fileId;
            //操作完成
            // reader.onload = function(e) {
            console.log("图片正在上传成功......", reader.result);
            imageItem.fileUrl = reader.result;
            this.imageList.push(imageItem);
            // let img = document.createElement("img");
            // img.src = reader.result
            // elem.appendChild(img)
            // };
          } else {
            return;
          }
        });
      }
    },
  },
};
</script>
<style lang="less">
.mark {
  flex-wrap: wrap;
  padding: 15px 15px 10px 20px !important;
  .weui-cell__hd {
    width: 100%;
    height: 20px;
    line-height: 20px;
    color: #101010;
  }
}
</style>
<style lang="less" scoped>
.registration {
  position: relative;
  background: #fff;
  padding-bottom: 88px;
  .submit-box {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 5px 0;
    background: #fff;
    z-index: 100;
    .submit-btn {
      width: 260px;
      border-radius: 20px;
      color: #fff;
      margin: 0 auto;
      border-color: rgb(205, 166, 105);
      background: rgb(205, 166, 105);
    }
  }
  .weui-label {
    color: #000;
  }
  .weui-input {
    text-align: right;
  }
  .weui-cells {
    position: relative;
  }
  .weui-cell:before {
    left: 0;
  }
  .form {
    // color: #8a8a8a;
    .scan {
      display: flex;
      justify-content: flex-end;
      font-size: 14px;
      .scan-content {
        height: 30px;
        border-radius: 15px;
        display: flex;
        width: 80px;
        align-items: center;
        padding: 0 20px;
        border: 1px solid #f1f1f1;
        margin: 0 10px 10px;

        img {
          width: 24px;
          margin-right: 10px;
        }
      }
    }
    .block-tips {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex-wrap: wrap;
      padding: 20px;
      gap: 10px;
      div {
        display: inline-block;
        padding: 0 15px;
        border-radius: 14px;
        height: 28px;
        line-height: 28px;
        font-size: 13px;
        background: #f1f1f1;
      }
      .active-tips {
        background: #4e5dba;
        color: #fff;
      }
      .tips-line {
        color: #4e5dba;
        background: #fff;
        border: 1px solid #4e5dba;
      }
    }
  }
}
.add-tag {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 15px;
}
.check-tags-box {
  .title {
    color: #999;
    padding-left: 15px;
    font-size: 14px;
  }
}
.check-tags {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
  padding: 20px;
  gap: 10px 15px;

  div {
    display: inline-block;
    padding: 0 15px;
    border-radius: 14px;
    height: 28px;
    line-height: 28px;
    font-size: 13px;
    background: #f1f1f1;
    position: relative;

    .close-icon {
      position: absolute;
      font-size: 12px;
      top: -10px;
      right: -20px;
      width: 24px;
      height: 24px;
      /* color: #999; */
      fill: #999;
    }
  }
  .active-tips {
    background: #4e5dba;
    color: #fff;
  }
}
.add-tag-btn {
  width: 110px;
  height: 32px;
  border-radius: 20px;
  font-size: 12px;
  color: #fff;
  margin: 0;
  border-color: rgb(205, 166, 105);
  background: rgb(205, 166, 105);
}
.confirm-tag-btn {
  width: 80%;
  margin: 0 auto;
  color: #fff;
  border-radius: 20px;
  border-color: rgb(205, 166, 105);
  background: rgb(205, 166, 105);
}
.choose-tag {
  max-height: 80%;
  background: #fff;
}

.file-box {
  padding: 10px 20px;

  .fa-plus-square-o {
    font-size: 50px;
    color: #d9d9d9;
    position: relative;
    width: 50px;
    height: 50px;

    input {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      opacity: 0;
    }
  }
  /deep/#instruction-pic {
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    img {
      margin-right: 8px;
      width: 125px;
      height: auto;
      border-radius: 4px;
    }
    .instruction-pic-item {
      position: relative;
      margin-right: 10px;
    }
    .fa-close {
      position: absolute;
      top: -5px;
      right: -5px;
      color: #999;
      font-size: 14px;
      font-weight: 300;
    }
  }
}
.upload-img {
  padding: 20px 20px 0 20px;
  font-size: 16px;
}
</style>
